package com.jms.web.mvc.resolver;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class ParamTypeConverter {
    private static final Map<Class<?>, Function<String, Object>> converterMap = new HashMap<>();

    static {
        converterMap.put(int.class, Integer::parseInt);
        converterMap.put(long.class, Long::parseLong);
        converterMap.put(double.class, Double::parseDouble);
        converterMap.put(float.class, Float::parseFloat);
        converterMap.put(boolean.class, Boolean::parseBoolean);
        converterMap.put(char.class, s -> s.charAt(0));
        converterMap.put(short.class, Short::parseShort);
        converterMap.put(byte.class, Byte::parseByte);
        converterMap.put(Float.class, Float::valueOf);
        converterMap.put(Double.class, Double::valueOf);
        converterMap.put(BigDecimal.class, BigDecimal::new);
        converterMap.put(BigInteger.class, BigInteger::new);
        converterMap.put(String.class, s -> s);
        converterMap.put(Boolean.class, Boolean::valueOf);
        converterMap.put(Byte.class, Byte::valueOf);
        converterMap.put(Short.class, Short::valueOf);
        converterMap.put(Integer.class, Integer::valueOf);
        converterMap.put(Character.class, s -> s.charAt(0));
        converterMap.put(Long.class, Long::valueOf);
    }

    /**
     * 将字符串值转换为目标类型对象
     *
     * @param type  目标类型
     * @param value 字符串值
     * @return 转换后的对象，如果value为null则返回null
     */
    public static Object convert(Class<?> type, String value) {
        if (value == null) {
            return null;
        }
        Function<String, Object> converter = converterMap.get(type);
        if (converter != null) {
            return converter.apply(value);
        } else {
            return type.cast(value);
        }
    }
}
